package com.dindang.checkline.mvp.presenter;

import android.app.Application;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.view.View;
import android.view.ViewTreeObserver;

import com.dindang.checkline.R;
import com.dindang.checkline.app.utils.AddPicUtils;
import com.dindang.checkline.app.utils.MyUtils;
import com.dindang.checkline.app.utils.NetworkUtils;
import com.dindang.checkline.mvp.greendao.controller.CheckItemController;
import com.dindang.checkline.mvp.greendao.controller.CheckItemDetailController;
import com.dindang.checkline.mvp.greendao.entity.CheckItem;
import com.dindang.checkline.mvp.model.entity.BaseResponse;
import com.dindang.checkline.mvp.model.entity.ItemDetailEntity;
import com.dindang.checkline.mvp.model.entity.LineEvent;
import com.dindang.checkline.mvp.model.entity.TaskEvent;
import com.dindang.checkline.mvp.ui.activity.adapter.costom.GridImageAdapter;
import com.dindang.checkline.mvp.ui.activity.witget.FullyGridLayoutManager;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;

import javax.inject.Inject;

import com.dindang.checkline.mvp.contract.CheckingContract;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;
import com.longxi.gamer_base.dialog.WaitDialog;
import com.longxi.gamer_base.utils.DateTimeUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;

import org.greenrobot.eventbus.EventBus;

import java.io.FileNotFoundException;
import java.util.Date;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 03/07/2019 15:01
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class CheckingPresenter extends BasePresenter<CheckingContract.Model, CheckingContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private GridImageAdapter mGridImageAdapter;
    private AddPicUtils mAddPicUtils;
    private int imageWidth = 0;
    private int maxSelectNum = 3;// 图片最大可选择数
    private int nomal = 0;//0正常，1异常
    private WaitDialog mWaitDialog;
    private ItemDetailEntity.DetailParam mParam = new ItemDetailEntity.DetailParam();
    private String itemId,piontId;//巡检项id,巡检点id
    private ItemDetailEntity mData = new ItemDetailEntity();
    private LineEvent mLineEvent = new LineEvent();
    private TaskEvent taskEvent = new TaskEvent();

    @Inject
    public CheckingPresenter(CheckingContract.Model model, CheckingContract.View rootView) {
        super(model, rootView);
    }

    public void init() {
        mWaitDialog = new WaitDialog(mRootView.getActivity());
        itemId = mRootView.getActivity().getIntent().getStringExtra("id");
        piontId = mRootView.getActivity().getIntent().getStringExtra("piontId");
        initSelectImage();//设置图片
        setData();//设置数据显示
    }

    private void setData() {
        mRootView.getTvLineName().setText("路线名称：路线路线2");
        mRootView.getTvLineAddress().setText("位置：3单元3楼3号灯");
        mRootView.getTvCheckWay().setText("巡检方式：走路");
        mRootView.getTvCheckContent().setText("内容以及注意事项：请检查灯有没有开着");
        mRootView.getIvNomal().setSelected(true);
        mRootView.getRlnomal().setOnClickListener(v -> setNomale());
        mRootView.getRlunnomal().setOnClickListener(v -> setNomale());
        mRootView.getButtonSbumit().setOnClickListener(v -> postData());
    }

    private void setNomale() {
        if (nomal == 0) {
            nomal = 1;
            mRootView.getIvUnnomal().setSelected(true);
            mRootView.getIvNomal().setSelected(false);
            mRootView.getClUnnomalDescribe().setVisibility(View.VISIBLE);
        } else {
            nomal = 0;
            mRootView.getIvNomal().setSelected(true);
            mRootView.getIvUnnomal().setSelected(false);
            mRootView.getClUnnomalDescribe().setVisibility(View.GONE);
        }
    }

    private void postData() {//点击提交
        mData.setItemId(Long.parseLong(itemId));
        mData.setRemarks(mRootView.getEtRemark().getText().toString());
        mData.setUnomalDescribe(mRootView.getEtUnnomalDescribe().getText().toString());
        if (mRootView.getIvNomal().isSelected()) {
            mData.setStatus("1");
        } else {
            mData.setStatus("8");
        }
        mData.setUserid(BaseAppConst.accountInfo.getUserId()+"");
        StringBuffer str = new StringBuffer();
        if(mAddPicUtils.selectList!=null&&mAddPicUtils.selectList.size()>0){
            for (int i = 0; i < mAddPicUtils.selectList.size(); i++) {
                if (i==0){
                    str.append(mAddPicUtils.selectList.get(0).getCompressPath());
                }else {
                    str.append(","+mAddPicUtils.selectList.get(i).getCompressPath());
                }
            }
        }
        mData.img = str.toString();
        mData.setCheckTime(DateTimeUtils.dateToYearMonthDayHour(new Date(System.currentTimeMillis())));
        mData.setPointid(Long.parseLong(piontId));
        if (!NetworkUtils.isAvailable(mApplication)) {
            //无网，插入到本地数据库
            Long l = CheckItemDetailController.insertItemDetail(mData);
            if (l > 0) {
                changeStatus();
            }
        }else{
        //以下是真实调接口
        mWaitDialog.showWaitingDialog(ArmsUtils.getString(mApplication, R.string.data_load));
            try {
                mModel.submitItemDetail(mData)
                        .subscribeOn(Schedulers.io())
                        .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                        .doOnSubscribe(disposable -> {

                        }).subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .doFinally(() -> {
                            mWaitDialog.hideWaitingDialog();
                        })
                        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                        .subscribe(new ErrorHandleSubscriber<BaseResponse>(mErrorHandler) {
                            @Override
                            public void onNext(BaseResponse response) {
                                if (response.getStatus().equals(BaseAppConst.OUT_TOKEN)) {
                                    MyApplication.getInstance().gotoLoginActivity();
                                }
                                if (response.isSuccess()) {
                                    mRootView.getActivity().finish();
                                   changeStatus();
                                }
                                ArmsUtils.makeText(mRootView.getActivity(), response.getStatuMsg());
                            }

                            @Override
                            public void onError(Throwable t) {
                                super.onError(t);

                            }
                        });
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    private void changeStatus() {
        CheckItem item = new CheckItem();
        item.setL_id(mData.getItemId());
        if (mData.getStatus().equals("1")) {
            item.setC_status("1");
        } else {
            item.setC_status("8");
        }
        CheckItemController.changeStatus(item);
        mLineEvent.setPiontId(mData.pointid);
        mLineEvent.setFinishTime(DateTimeUtils.dateToYearMonthDayHour(new Date(System.currentTimeMillis())));
        EventBus.getDefault().post(mLineEvent);
        EventBus.getDefault().post(taskEvent);
        mRootView.getActivity().finish();
    }

    private void initSelectImage() {
        mRootView.getTvCheckNumTip().setText("可选，最多支持添加" + maxSelectNum + "张图片");
        setPicRemainNumTip(0);
        mAddPicUtils = new AddPicUtils(mRootView.getActivity());
        mAddPicUtils.setSelectMax(maxSelectNum);
        mGridImageAdapter = new GridImageAdapter(mRootView.getRecyclerView().getContext(), mAddPicUtils.onAddPicClickListener);
        mGridImageAdapter.setList(mAddPicUtils.selectList);
        mGridImageAdapter.setSelectMax(maxSelectNum);
        mRootView.getRecyclerView().setAdapter(mGridImageAdapter);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(mRootView.getRecyclerView().getContext(), 4, GridLayoutManager.VERTICAL, false);
        mRootView.getRecyclerView().setLayoutManager(manager);
        ViewTreeObserver vto = mRootView.getRecyclerView().getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                if (imageWidth == 0) {
                    imageWidth = mRootView.getRecyclerView().getMeasuredWidth();
                    mGridImageAdapter.setImageWidth(imageWidth);
                }
                return true;
            }
        });

        mGridImageAdapter.setOnRemainNumListener(new GridImageAdapter.OnRemainNumListener() {
            @Override
            public void onItemClick(int remainNum) {
                setPicRemainNumTip(remainNum);
            }
        });
    }

    /**
     * activity回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != mRootView.getActivity().RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                mAddPicUtils.selectList = PictureSelector.obtainMultipleResult(data);
                mGridImageAdapter.setList(mAddPicUtils.selectList);
                mGridImageAdapter.notifyDataSetChanged();
                setPicRemainNumTip(mAddPicUtils.selectList.size());
                break;
        }
    }

    private void setPicRemainNumTip(int remain) {
        mRootView.getTvCheckNum().setText(remain + "/" + maxSelectNum);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        this.mGridImageAdapter = null;
        this.mAddPicUtils = null;
    }
}
